package com.geek.aidy.geek.annotation;

import java.lang.reflect.Field;
import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.geek.aidy.geek.enums.DesensitizeType;

@Aspect
@Component
public class DesensitizeAspect {
 @Around("execution(* com.geek.aidy.geek.controller..*.*(..))")
    public Object desensitize(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = joinPoint.proceed();
        handleResult(result);
        return result;
    }

    private void handleResult(Object result) {
        if (result == null) {
            return;
        }
        if (result instanceof List) {
            ((List<?>) result).forEach(this::processObject);
        } else {
            processObject(result);
        }
    }

    private void processObject(Object obj) {
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            Desensitize desensitize = field.getAnnotation(Desensitize.class);
            if (desensitize != null) {
                field.setAccessible(true);
                try {
                    Object value = field.get(obj);
                    if (value instanceof String) {
                        String strValue = (String) value;
                        String desensitized = desensitizeValue(strValue, desensitize.type());
                        field.set(obj, desensitized);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String desensitizeValue(String value, DesensitizeType type) {
        switch (type) {
            case NAME:
                return desensitizeName(value);
            case PHONE:
                return desensitizePhone(value);
            default:
                return value;
        }
    }

    private String desensitizeName(String name) {
        if (name == null || name.isEmpty()) {
            return name;
        }
        return name.replaceAll("^(\\S).*", "$1*");
    }

    private String desensitizePhone(String phone) {
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }
}
